<template>
  <el-dialog title="分配权限" :visible="visible" width="500px" @close="onCloseDialog">
    <el-tree ref="permissionTreeRef" check-strictly :data="permissionList" show-checkbox default-expand-all :props="{ label: 'name'}" node-key="id" />
    <el-row type="flex" justify="center">
      <el-button type="primary" size="middle" @click="onSaveAssignPermission">确定</el-button>
      <el-button size="middle" @click="onCloseDialog">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { getRoleDetailAPI, assignPermissionsAPI } from '@/api/role'
import { transListToTreeData } from '@/utils'

export default {
  name: 'AssignPermission',
  data() {
    return {
      visible: false, // 控制弹窗的显示与隐藏
      roleId: null, // 当前角色的id
      permissionList: [], // 所有的权限列表
      permissionIds: [] // 当前角色已经拥有的权限id
    }
  },
  created() {
    // 获取所有的权限列表
    this.getPermissionList()
  },
  methods: {
    // 打开弹窗
    async open(id) {
      this.roleId = id
      // 获取当前角色已经拥有的权限id
      await this.getPermissionIds()
      // 为了显示效果，先获取数据再打开弹窗
      this.visible = true
      this.$nextTick(() => {
        // 设置选中的节点
        this.$refs.permissionTreeRef.setCheckedKeys(this.permissionIds)
      })
    },
    // 关闭弹窗，重置数据
    onCloseDialog() {
      this.visible = false
      this.roleId = null
      this.permissionIds = []
      // 清空选中的节点
      this.$refs.permissionTreeRef.setCheckedKeys([])
    },
    // 获取所有的权限列表
    async getPermissionList() {
      // 获取权限列表并转换为树形列表结构
      this.permissionList = transListToTreeData(await getPermissionListAPI(), 0)
    },
    // 获取当前角色已经拥有的权限id
    async getPermissionIds() {
      const { permIds } = await getRoleDetailAPI(this.roleId)
      this.permissionIds = permIds
    },
    // 保存分配的权限
    async onSaveAssignPermission() {
      await assignPermissionsAPI({ id: this.roleId, permIds: this.$refs.permissionTreeRef.getCheckedKeys() })
      this.$message.success('分配权限成功')
      // 关闭窗口，重置数据
      this.onCloseDialog()
    }
  }
}
</script>

<style>

</style>
